package com.wongoing.sys.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.wongoing.base.PageResult;
import com.wongoing.sys.model.SysPermission;
import com.wongoing.sys.model.SysRolePermission;
import com.wongoing.sys.model.SysUser;
import com.wongoing.sys.model.ext.SysPermissionExt;
import com.wongoing.sys.model.ext.SysRolePermissionExt;
import com.wongoing.sys.service.SysPermissionService;
import com.wongoing.sys.service.SysRolePermissionService;
import com.wongoing.sys.service.SysUserService;
import com.wongoing.sys.viewmodel.JsonResult;
import com.wongoing.util.LogService;
import com.wongoing.util.ModelAndViewConstants;
import com.wongoing.util.PageUtil;

@Controller
@RequestMapping(value = "/sys/sysRolePermissionAction")
public class SysRolePermissionAction extends BaseAction{
	private SysRolePermissionService service;
	private SysPermissionService sysPermissionService;
	private SysUserService sysUserService;

	@Autowired
	public void setService(SysRolePermissionService service) {
		this.service = service;
	}
	
	@Autowired
	public void setSysPermissionService(SysPermissionService sysPermissionService) {
		this.sysPermissionService = sysPermissionService;
	}

	@Autowired
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}
	
	/**
	 * 功能说明：进入列表显示界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:58:49
	 * @param pageSize 每页记录数
	 * @param pageCurrent 当前页索引
	 * @param orderField 排序字段
	 * @param orderDirection 排序方向
	 * @param paramName 参数：名称
	 * @param paramDescription 参数：描述
	 * @return
	 */
	@RequestMapping(value = "/toList")
	public ModelAndView toList(Integer pageSize, Integer pageCurrent, String orderField, String orderDirection,
			String paramName, String paramDescription){
		
		ModelAndView mv = null;
		try {
			PageResult<SysRolePermissionExt> pageResult = PageUtil.pageSet(this.getClass(), pageSize, pageCurrent, orderField, orderDirection);
			//模糊查询条件
			List<Boolean> multiFuzzyQuery = new ArrayList<Boolean>();
			if(paramName!=null && !"".equals(paramName)){
				pageResult.getParam().put("name", paramName);
				pageResult.setOrderField("sr.Name");
				pageResult.setOrderDirection("DESC");
				pageResult.getExt().put("paramName", paramName);
				multiFuzzyQuery.add(true);
			}else{
				multiFuzzyQuery.add(false);
			}
			if(paramDescription!=null && !"".equals(paramDescription)){
				pageResult.getParam().put("description", paramDescription);
				pageResult.setOrderField("sr.Description");
				pageResult.setOrderDirection("DESC");
				pageResult.getExt().put("paramDescription", paramDescription);
				multiFuzzyQuery.add(true);
			}else{
				multiFuzzyQuery.add(false);
			}
			if(PageUtil.multiFuzzyQuery(multiFuzzyQuery)){
				pageResult.setOrderField("sr.Id");
				pageResult.setOrderDirection("ASC");
			}
			pageResult = this.service.getRolePermissionListPageReuslt(pageResult);
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.PAGE_RESULT, pageResult);
			mv.setViewName(ModelAndViewConstants.ROLE_PERMISSION_CONFIG_MAIN_VIEW);	
			LogService.getInstance(this).debug("角色权限分配数据列表获取成功："+ModelAndViewConstants.USER_ROLE_MAIN_VIEW);
		} catch (Exception ex) {
			LogService.getInstance(this).error("角色权限分配列表分页数据获取失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		
		return mv;
	}
	
	/**
	 * 功能说明：进入编辑界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:59:41
	 * @param roleId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toEdit")
	public List<SysPermissionExt> toEdit(Integer roleId){
		List<SysPermissionExt> resultList = null;
		try {
			String status = "0";
			String isUsed = "Y";
			List<SysPermissionExt> perList = this.sysPermissionService.getPermissionListByParam(status, isUsed);
			for (SysPermissionExt list : perList) {
				System.out.println("所有功能有："+list.getId()+","+list.getName() + "," + list.getParentId() + " ," + list.getParentName());
			}
			List<SysPermission> rolePerList = this.sysPermissionService.getByRoleId(roleId, status);
			resultList = new ArrayList<SysPermissionExt>();
			for (SysPermissionExt spe : perList) {
				spe.setChecked(false);
				for (SysPermission sp : rolePerList) {
					if(spe.getId().equals(sp.getId())){
						spe.setChecked(true);
					}
				}
				resultList.add(spe);
			}
		} catch (Exception e) {
			resultList = new ArrayList<SysPermissionExt>();
		}
		return resultList;
	}
	
	/**
	 * 功能说明：执行保存操作
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午1:00:01
	 * @param roleId
	 * @param permissionIdStr
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doSave")
	public Map<String,Object> doSave(Integer roleId, String permissionIdStr){
		Map<String, Object> jsonResult = null;
		try {
			String tabid = tabid(ModelAndViewConstants.ROLE_PERMISSION_SYS_ID);
			//1.根据roleId删除对应角色下的权限信息
			Map<String,Object> roleParam = new HashMap<String, Object>();
			roleParam.put("roleId",roleId);
			this.service.deleteByParam(roleParam);
			//2.设置新的权限id集合
			if(!permissionIdStr.isEmpty()){
				List<SysRolePermission> insertList = new ArrayList<SysRolePermission>();
				String[] permissionIdArr = permissionIdStr.split(",");
				for (String permissionId : permissionIdArr) {
					SysRolePermission srp = new SysRolePermission();
					srp.setRoleId(roleId);
					srp.setPermissionId(Integer.parseInt(permissionId));
					srp.setStatus("0");
					String currentName =  SecurityUtils.getSubject().getPrincipal().toString();
					Map<String, Object> userParam = new HashMap<String, Object>();
					userParam.put("account", currentName);
					List<SysUser> userList = this.sysUserService.getByParam(userParam);
					if(userList!=null && !userList.isEmpty()){
						srp.setCreateUser(userList.get(0).getId());
						srp.setModifyUser(userList.get(0).getId());
					}else{
						srp.setCreateUser(1);
						srp.setModifyUser(1);
					}
					srp.setCreateDate(new Date());
					srp.setModifyDate(new Date());
					insertList.add(srp);
				}
				//3.批量插入
				this.service.insertBatch(insertList);
			}
			Integer statusCode = 200;
			String msg = "权限分配成功！";
			jsonResult = JsonResult.jsonReturn(statusCode.intValue(), msg, tabid);
			LogService.getInstance(this).debug("权限分配成功!");	
		} catch (Exception ex) {
			String msg = "保存权限分配信息失败";
			jsonResult = JsonResult.jsonReturnErr(msg);
			LogService.getInstance(this).debug("保存权限分配信息失败!"+ex.getMessage());
		}
		return jsonResult;
	}
	
	/**
	 * 功能说明：进入详情界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午1:00:29
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value = "/toDetails")
	public ModelAndView toDetails(Integer roleId){
		ModelAndView mv = null;
		try {
			String status = "0";
			String isUsed = "Y";
			List<SysPermissionExt> perList = this.sysPermissionService.getPermissionListByParam(status, isUsed);
			List<SysPermission> rolePerList = this.sysPermissionService.getByRoleId(roleId, status);
			List<SysPermissionExt> resultList = new ArrayList<SysPermissionExt>();
			for (SysPermissionExt spe : perList) {
				spe.setChecked(false);
				spe.setChkDisabled(true);
				for (SysPermission sp : rolePerList) {
					if(spe.getId().equals(sp.getId())){
						spe.setChecked(true);
					}
				}
				resultList.add(spe);
			}
			mv = new ModelAndView();
			mv.addObject("perList", OutputJson(resultList));
			mv.setViewName(ModelAndViewConstants.ROLE_PERMISSION_CONFIG_DETAILS_VIEW);
		} catch (Exception e) {
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}
}
